// 云函数入口文件
const cloud = require('wx-server-sdk')
const {
  WINTER_START_DATE,
  SUMMER_START_DATE
} = require('./config');
const ResponseDTO = require('./res');
const dayjs = require('dayjs');
const util = require('./util');
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database();
const USER = 'edu-cloud-users'
// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext();
  // 获取当前开始日期
  let defaultParams = util.calcDefault();
  // 获取当前用户是否绑定教务系统
  let queryRes = await db.collection(USER).where({
    openid:wxContext.OPENID
  }).get();
  //学号
  let eduId = '';
  if (queryRes.data.length != 0) {
    eduId = queryRes.data[0].bindId;
  }
  //如果学号不为 0 调用 token flush API
  if(eduId != '' && eduId != undefined && eduId != null){
    //调用TOKEN刷新
    cloud.callFunction({
      name:'token-flush',
      data:{
        openid:wxContext.OPENID
      }
    })
  }
  return ResponseDTO.succData({
    eduId,
    ...defaultParams,
    openid: wxContext.OPENID,
    appid: wxContext.APPID,
    unionid: wxContext.UNIONID,
  })
}